package com.itheima.stock.utils;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

public class Zifuchuang19wei {
//    private  final Set<Long> generatedNumbers = new HashSet<>();
//    private  final int NUMBER_LENGTH = 19;
//
//    public  void main(String[] args) {
//        System.out.println(generateUniqueNumber());
//    }
//
//    public  synchronized long generateUniqueNumber() {
//        long number;
//        do {
//            // Generate a 64-bit number and shift it to make sure we have enough digits.
//            number = ThreadLocalRandom.current().nextLong(1L << 60);
//        } while (!isUnique(number));
//
//        // Save the number to prevent duplicates.
//        generatedNumbers.add(number);
//        return number;
//    }
//
//    private  boolean isUnique(long number) {
//        String numStr = Long.toString(number);
//        if (numStr.length() > NUMBER_LENGTH) {
//            numStr = numStr.substring(0, NUMBER_LENGTH);
//        }
//        return !generatedNumbers.contains(Long.parseLong(numStr));
//    }
//
//    public  String formatNumber(long number) {
//        String numStr = Long.toString(number);
//        if (numStr.length() < NUMBER_LENGTH) {
//            // Pad with leading zeros if necessary.
//            numStr = String.format("%0" + NUMBER_LENGTH + "d", number);
//        } else if (numStr.length() > NUMBER_LENGTH) {
//            numStr = numStr.substring(0, NUMBER_LENGTH);
//        }
//        return numStr;
//    }
    private  final Set<Long> generatedNumbers = new HashSet<>();
    private  final int NUMBER_LENGTH = 19;
    private  final long PREFIX = 124L * (long)Math.pow(10, 16); // 前缀124，后面跟16个0

    public  void main(String[] args) {
        System.out.println(generateUniqueNumberWithPrefix());
    }

    public  synchronized long generateUniqueNumberWithPrefix() {
        long number;
        do {
            // Generate a 16-bit number and add the prefix to ensure the number starts with 124.
            number = PREFIX + ThreadLocalRandom.current().nextLong(1L << 48);
        } while (!isUnique(number));

        // Save the number to prevent duplicates.
        generatedNumbers.add(number);
        return number;
    }

    private  boolean isUnique(long number) {
        return !generatedNumbers.contains(number);
    }

    public  String formatNumber(long number) {
        String numStr = Long.toString(number);
        if (numStr.length() < NUMBER_LENGTH) {
            // Pad with leading zeros if necessary, but here it should not be needed since we're generating 19 digits.
            numStr = String.format("%0" + NUMBER_LENGTH + "d", number);
        }
        return numStr;
    }
}
